package com.bndg.shu.shuyinyangshi.activitys;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bndg.shu.shuyinyangshi.MyApp;
import com.bndg.shu.shuyinyangshi.R;
import com.bndg.shu.shuyinyangshi.entity.BaseEntity;
import com.bndg.shu.shuyinyangshi.request.RequestManager;
import com.bndg.shu.shuyinyangshi.service.FloatViewService;
import com.bndg.shu.shuyinyangshi.ui.popupwindow.PopupWindowUtil;
import com.bndg.shu.shuyinyangshi.utils.AlterWindowUtil;
import com.bndg.shu.shuyinyangshi.utils.ToastUtils;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    public static boolean IS_OPEN_SERVICE = false;
    @Bind(R.id.iv_main_open)
    ImageView ivMainOpen;
    @Bind(R.id.iv_main_close)
    ImageView ivMainClose;
    @Bind(R.id.iv_background)
    ImageView ivBackground;
    @Bind(R.id.iv_help)
    ImageView ivHelp;
    @Bind(R.id.tv_help)
    TextView tvHelp;
    @Bind(R.id.iv_query)
    View iv_query;
    @Bind(R.id.bt_query)
    View bt_query;
    @Bind(R.id.sp_choose)
    Spinner sp_choose;
    private long nowTime;
    private long beforeTime;
    private PopupWindowUtil popupWindowUtil;
    private TranslateAnimation ta_goright;
    private TranslateAnimation ta_goleft;
    private View fl;
    private View rl;
    private HashMap<String, String> paramsMap;
    private boolean isExists;
    private List<String> uids = new ArrayList<>();
    //    private BaseAdapter adapter;
    private ArrayAdapter<String> adapter;
    private List<String> uidKeys = new ArrayList<>();
    private boolean isShow = false;
    private boolean isShowing;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Logger.d("on creat");
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        //创建ArrayAdapter对象
       /* adapter = new BaseAdapter() {
            class ViewHolder {
                TextView textView;
            }

            @Override
            public int getCount() {
                return uids.size();
            }

            @Override
            public Object getItem(int position) {
                return uids.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                ViewHolder viewHolder;
                if(convertView == null) {
                    convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.sp_item, parent, false);
                    viewHolder = new ViewHolder();
                    viewHolder.textView = (TextView) convertView.findViewById(R.id.tv_choose);
                    convertView.setTag(viewHolder);
                }else {
                    viewHolder = (ViewHolder) convertView.getTag();
                }
                viewHolder.textView.setText(uids.get(position));
                return convertView;
            }
        };*/
        // 建立Adapter并且绑定数据源
        uidKeys.add("获取id");
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, uidKeys);
        adapter.setDropDownViewResource(android.R.layout.simple_list_item_multiple_choice);
        sp_choose.setAdapter(adapter);
        copyAddressDB();
    }

    @Override
    protected void onStart() {
        Logger.d("on start");
        super.onStart();
    }

    @Override
    protected void onRestart() {
        Logger.d("on restart");
        super.onRestart();
    }

    private void startAnim() {
        ScaleAnimation sa = new ScaleAnimation(0.9f, 1.1f, 0.9f, 1.1f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        sa.setInterpolator(new LinearInterpolator());
        sa.setRepeatCount(Animation.INFINITE);
        sa.setRepeatMode(Animation.REVERSE);
        sa.setDuration(2500);
        ivMainOpen.startAnimation(sa);
        ivMainClose.startAnimation(sa);
    }

    @Override
    protected void onResume() {
        Logger.d("on Resume");
        super.onResume();
        startAnim();
    }

    @Override
    protected void onPause() {
        Logger.d("on pause");
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeFloatView();
    }

    /**
     * 拷贝归属地的数据库
     */
    private void copyAddressDB() {
        File file = new File(getFilesDir(), "shuyys.db");
        //判断数据库文件是否存在
        if (file.exists() && file.length() > 0) {
            Logger.d("数据库存在");
        } else {
            new Thread() {
                public void run() {
                    // 把asset资产目录里面的数据库文件(在apk里面的)拷贝到手机系统里面
                    try {
                        InputStream is = getAssets().open("shuyys.db");
                        File file = new File(getFilesDir(), "shuyys.db");
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] buffer = new byte[1024];
                        int len = -1;
                        while ((len = is.read(buffer)) != -1) {
                            fos.write(buffer, 0, len);
                        }
                        fos.close();
                        is.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

    @OnClick({R.id.iv_main_open, R.id.iv_main_close, R.id.tv_help, R.id.iv_help, R.id.iv_query, R.id.bt_query})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_main_open:
                if (AlterWindowUtil.isFloatWindowOpAllowed(MyApp.mContext)) {
//                    rotateAnim(ivMainOpen, true);
                    startFloatView();
                } else {
                    ToastUtils.MakeToast("去应用权限那里开悬浮窗权限");
                }
                break;
            case R.id.iv_main_close:
//                rotateAnim(ivMainClose, false);
                closeFloatView();
                break;

            case R.id.iv_help:
            case R.id.tv_help:
//                rotateAnim(ivMainClose, false);
                showPopupwindow();
//                paramsMap = new HashMap<>();
//                RequestManager.getInstance(this).requestAsyn("zt/yys/xsfy/data/tsfbData.js", RequestManager.TYPE_GET, paramsMap, new JsonCallBack<BaseEntity>() {
//
//                });
                break;
            case R.id.bt_query:
                goQuery();
                break;
            case R.id.iv_query:
                uids.clear();
                uidKeys.clear();
                //   /com.netease.onmyoji.wdj
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //用户已经拒绝过一次，再次弹出权限申请对话框需要给用户一个解释
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission
                            .WRITE_EXTERNAL_STORAGE)) {
                    }
                    //申请权限
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);

                } else {
                    Logger.e("checkPermission: 已经授权！");
                    findUid();
                }

                break;
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //TODO:已授权
            findUid();
        } else {
            //TODO:用户拒绝
            Toast.makeText(this, "请开通相关权限，否则无法正常使用本应用！", Toast.LENGTH_SHORT).show();
        }
    }

    private void findUid() {
        String path = Environment.getExternalStorageDirectory().getPath();
        File parentFile = new File(path + "/Android/data/");
        File yysFile = null;
        if (parentFile.exists() && parentFile.isDirectory()) {
            File[] files = parentFile.listFiles();
            for (File file1 : files) {
                if (file1.getName().startsWith("com.netease.onmyoji") && file1.isDirectory()) {
                    isExists = true;
                    try {
                        yysFile = new File(file1.getCanonicalPath() + "/files/netease/onmyoji");
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    break;
                }
            }
            if (!isExists || yysFile == null) {
                ToastUtils.MakeToast("没有发现阴阳师的文件夹,确认安装游戏了吗?");
            } else {
                int count = 0;
                for (File file1 : yysFile.listFiles()) {
                    if (file1.getName().startsWith("chat") && file1.isDirectory()) {
                        String name = file1.getName();
                        int i = name.lastIndexOf("_");
                        if (i != -1) {
                            String uid = name.substring(i + 1);
                            uids.add(uid);
                            uidKeys.add("角色" + ++count);
                        }
                    }
                }
                if (uids.size() > 0) {
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }

    private void goQuery() {
        if (uidKeys.size() == 0 || "获取id".equals(sp_choose.getSelectedItem().toString())) {
            ToastUtils.MakeToast("没有获取到id");
            return;
        }
        if (uids.size() > 0) {
            String uid = uids.get(sp_choose.getSelectedItemPosition());
            Intent intent = new Intent(MainActivity.this, ShuWebviewActivity.class);
            intent.putExtra(Constant.UDID, uid);
            startActivity(intent);
        }
    }

    private void showPopupwindow() {
        if (isShowing) {
            return;
        }
        if (popupWindowUtil == null) {
            popupWindowUtil = new PopupWindowUtil(ivHelp);
            popupWindowUtil.setContentView(R.layout.help_layout);
            fl = popupWindowUtil.findId(R.id.fl_help_contain);
            rl = popupWindowUtil.findId(R.id.rl_content);
            ta_goright = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f);
            ta_goright.setDuration(1000);
            ta_goright.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    isShowing = true;
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    isShow = true;
                    isShowing = false;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            ta_goleft = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, -1.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f);
            ta_goleft.setDuration(1000);
            ta_goleft.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    rl.setVisibility(View.VISIBLE);
                    isShowing = true;
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    isShow = true;
                    isShowing = false;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        if (isShow) {
            TranslateAnimation translateAnimation = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, -1.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f);
            translateAnimation.setDuration(1000);
            translateAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    isShowing = true;
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    isShow = false;
                    isShowing = false;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            translateAnimation.setFillAfter(true);

            TranslateAnimation ta = new TranslateAnimation(
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 1.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f,
                    Animation.RELATIVE_TO_SELF, 0.0f);
            ta.setDuration(1000);
            ta.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {
                    isShowing = true;
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    isShow = false;
                    isShowing = false;
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
            ta.setFillAfter(true);
            rl.startAnimation(ta);
            fl.startAnimation(translateAnimation);
        } else {
            fl.startAnimation(ta_goleft);
            rl.startAnimation(ta_goright);
        }
        popupWindowUtil.showRight();
    }

    private void rotateAnim(View target, final boolean is_start) {

        Timer timer = new Timer();

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                if (is_start) {
                    startFloatView();
                } else {
                    closeFloatView();
                }
            }
        };

        timer.schedule(timerTask, 450);
    }

    @Override
    protected void onStop() {
        Logger.d("on stop");
        ivMainOpen.clearAnimation();
        ivMainClose.clearAnimation();
        super.onStop();
    }

    private void startFloatView() {
        try {
            Intent intent = new Intent(this, FloatViewService.class);
            startService(intent);
            bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
            moveTaskToBack(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void closeFloatView() {
        try {
            if (IS_OPEN_SERVICE) {
                unbindService(mServiceConnection);
                stopService(new Intent(this, FloatViewService.class));
                IS_OPEN_SERVICE = false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onBackPressed() {
        nowTime = System.currentTimeMillis();
        if (nowTime - beforeTime > 2000) {
            beforeTime = System.currentTimeMillis();
            ToastUtils.MakeToast("再按一次返回键退出程序");
        } else {
            super.onBackPressed();
        }
    }

    private FloatViewService mFloatViewService;
    /**
     * 连接到Service
     */
    private final ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            mFloatViewService = ((FloatViewService.FloatViewServiceBinder) iBinder).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mFloatViewService = null;
        }
    };
}
